// src\components\sendBox\SideMenu.jsx
// 侧边栏Sider
import React, { useEffect, useState } from 'react'
import { Layout, Menu } from 'antd';
import { withRouter } from 'react-router-dom';
import {
  HomeOutlined,
  UserOutlined,
  UserAddOutlined,
  CheckSquareOutlined,
  AuditOutlined,
  PullRequestOutlined
} from '@ant-design/icons';
import axios from 'axios'
import {connect} from 'react-redux'

// 菜单图标映射表
const menuKeyToIcon = {
  "/home": <HomeOutlined />,
  "/user-manage": <UserOutlined />,
  "/right-manage": <UserAddOutlined />,
  "/news-manage": <CheckSquareOutlined />,
  "/audit-manage": <AuditOutlined />,
  "/publish-manage": <PullRequestOutlined />,

}
function formatteMenuList(item) {
  let { grade, id, key, pagepermisson, title, children } = item;
  if (!pagepermisson) {
    return;
  }
  let obj={};
  //空数组在逻辑上为true
  if (!item.children || !item.children.length) {
     obj = { grade, id, key, title, label: title, icon: menuKeyToIcon[key] };
  } else {
     obj = { grade, id, key, pagepermisson, title, label: title, children: children.map(e => formatteMenuList(e)) };
  }
  return Object.assign(obj,{icon:menuKeyToIcon[key]});
}
//UI部分
function SideMenu(props) {
  // console.log("---------",props);
  const [menuList, setmenuList] = useState([]);
  // 初始化从模拟接口获取到动态的导航菜单数据
  useEffect(() => {
    axios.get('http://localhost:8888/rights?_embed=children').then(res => {
      // console.log("get导航数据", res.data);
      const out = res.data.map(e => formatteMenuList(e));
      setmenuList(out);
    })
  }, [])
  const { Sider } = Layout;
  // 点击切换路由
  const changeContent = (e) => {
    return props.history.push(e.key);
  }
  return (
    <Sider trigger={null} collapsible collapsed={props.isCollapsed}>
      <div className="logo" >一个占位</div>
      <Menu
        theme="dark"
        mode="inline"
        defaultSelectedKeys={['1']}
        items={menuList}
        onClick={changeContent}
      />
    </Sider>
  )
}

// 容器部分
const mapStateToProps=({CollApsedReducer:{isCollapsed}})=>{
  return {
    isCollapsed
  }
}
// 由于在侧边栏没有可以操作自身是否展开的功能的需求，所以这里可以没有mapDispatchToProps
export default connect(mapStateToProps)(withRouter(SideMenu));
